<template>
  <div>
    <div id="map"></div>
    <div ref="popup" class="popup" v-show="shopPopup">
      <span class="icon-close" @click.self="closePopup">✖</span>
      <div class="content">{{ "当前坐标为:" + currentCoordinate }}</div>
    </div>
    <div class="ol-control ol-unselectable locate">
      <button title="Locate me" @click="locate(localSource)">◎</button>
    </div>
  </div>
</template>

<script>
import "ol/ol.css";
import { Map, View, Feature } from "ol";
import Circle from "ol/geom/Circle";
import TileLayer from "ol/layer/Tile";
import WMTS from "ol/source/WMTS";
import { get as getProjection } from "ol/proj";
import { getWidth, getTopLeft } from "ol/extent";
import WMTSTileGrid from "ol/tilegrid/WMTS";
import { Point } from "ol/geom";
import Overlay from "ol/Overlay";
import { Style, Icon, Fill, Circle as CircleStyle, Stroke } from "ol/style";
import { Vector as SourceVec } from "ol/source";
import { Vector as LayerVec } from "ol/layer";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import GeoJSON from "ol/format/GeoJSON";
import { circular } from "ol/geom/Polygon";
import { fromLonLat } from "ol/proj";
import localInfo from "../model/getManyLocal";
// import func from '../../vue-temp/vue-editor-bridge';
// import Control from "ol/control/Control";
// import OSM from "ol/source/OSM";
export default {
  data() {
    return {
      map: null,
      shopPopup: false,
      popup: null,
      currentCoordinate: "",
      localList: [],
      localSource: null
    };
  },
  mounted() {
    // this.vectorTileLayer();
    this.init();
    this.vectorTileLayer();
    this.getLocation();
    this.getLocal();
    this.manyLocal();
  },
  methods: {
    init() {
      // var source = new XYZ({
      //   url: layerConfig.tileUrl+"{z}/{x}/{y}.jpg",
      // });
      const epsg = "EPSG:4326";
      const projection = getProjection(epsg);
      const projectionExtent = projection.getExtent();
      const size = getWidth(projectionExtent) / 256;
      const length = 19;
      const resolutions = new Array(length);
      const matrixIds = new Array(length);
      for (let i = 0; i < length; i += 1) {
        const pow = Math.pow(2, i);
        resolutions[i] = size / pow;
        matrixIds[i] = i;
      }
      var source = new WMTS({
        url:
          "http://t3.tianditu.com/img_c/wmts?tk=	d741c9b10fe94e0b9dd983b714de48fb",
        layer: "img",
        style: "default",
        matrixSet: "c",
        format: "tiles",
        wrapX: true,
        tileGrid: new WMTSTileGrid({
          origin: getTopLeft(projectionExtent),
          resolutions,
          matrixIds
        })
      });
      this.map = new Map({
        target: "map",
        layers: [
          new TileLayer({
            source: source
          })
        ],
        view: new View({
          projection: "EPSG:3857",
          center: [12729502.20562764, 3566970.780904669],
          extent: [
            [12725354.65223766, 3564822.181182724],
            [12733649.759017622, 3569119.380626613]
          ],
          minZoom: 10,
          maxZoom: 19,
          zoom: 15
        })
      });
    },
    getLocal() {
      localInfo.getManyLocal().then(res => {
        console.log(res.data);
      });
    },
    markOne(vectorSource) {
      this.map.on("click", evt => {
        this.shopPopup = true;
        var coordinate = evt.coordinate; //鼠标单击点的坐标
        this.currentCoordinate = coordinate;
        //新建一个要素ol.Feature
        console.log(coordinate);
        var newFeature = new Feature({
          geometry: new Point(coordinate), //几何信息
          name: "标注点"
        });
        newFeature.setStyle(this.createLabelStyle(newFeature)); //设置要素样式
        let elPopup = this.$refs.popup; //设置弹窗
        this.popup = new Overlay({
          element: elPopup,
          positioning: "bottom-center",
          stopEvent: true,
          autoPan: true, // 如果弹窗在底图边缘时，底图会移动
          autoPanAnimation: {
            // 底图移动动画
            duration: 250
          }
        });
        setTimeout(() => {
          // 设置弹窗位置
          // 这里要设置定时器，不然弹窗首次出现，底图会跑偏
          this.popup.setPosition(coordinate);
        }, 0);
        this.map.addOverlay(this.popup);
        vectorSource.addFeature(newFeature);
      });
    },
    // 关闭弹窗
    closePopup() {
      // 把弹窗位置设置为undefined，并清空坐标数据
      // this.overlay.setPosition(undefined);
      this.shopPopup = false;
    },
    vectorTileLayer() {
      // 创建矢量容器
      var vectorSource = new SourceVec({});
      //创建图标特性
      var iconFeature = new Feature({
        geometry: new Point([12728723.477446418, 3568390.720042001], "XY")
      });

      //将图标特性添加进矢量中
      vectorSource.addFeature(iconFeature);
      //创建图标样式
      var iconStyle = new Style({
        image: new Icon({
          opacity: 0,
          src:
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1594359193211&di=1d6bb819a5daa724ff65cc4d011d4d42&imgtype=0&src=http%3A%2F%2Fku.90sjimg.com%2Felement_pic%2F17%2F10%2F27%2F05dc60e54e3aa5d093cdc32611303643.jpg"
        })
      });
      //创建矢量层
      var vectorLayer = new LayerVec({
        source: vectorSource,
        style: iconStyle
      });
      //添加进map
      this.map.addLayer(vectorLayer);
      this.markOne(vectorSource);
    },
    createLabelStyle() {
      return new Style({
        image: new Icon({
          anchor: [0.5, 60], //锚点
          anchorOrigin: "top-right", //锚点源
          anchorXUnits: "fraction", //锚点X值单位
          anchorYUnits: "pixels", //锚点Y值单位
          offsetOrigin: "top-right", //偏移原点
          opacity: 0.75,
          scale: 0.05,
          src:
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1594359193211&di=1d6bb819a5daa724ff65cc4d011d4d42&imgtype=0&src=http%3A%2F%2Fku.90sjimg.com%2Felement_pic%2F17%2F10%2F27%2F05dc60e54e3aa5d093cdc32611303643.jpg" //图标的URL
        }),
        cursor: "point"
      });
    },
    getLocation() {
      const source = new VectorSource();
      navigator.geolocation.watchPosition(
        pos => {
          console.log(111);
          const coords = [pos.coords.longitude, pos.coords.latitude];
          const accuracy = circular(coords, pos.coords.accuracy);
          source.clear(true);
          source.addFeatures([
            new Feature(
              accuracy.transform(
                this.map.getView().getProjection(),
                "EPSG:3857"
              )
            ),
            new Feature(new Point(fromLonLat(coords)))
          ]);
          const layer = new VectorLayer({
            source: source
          });
          this.localSource = source;
          var brr = [];
          source.getExtent().forEach((item, index) => {
            if (index == 0 || index == 1) {
              brr.push(item);
            }
          });
          var crr = [];
          source.getExtent().forEach((item, index) => {
            if (index == 2 || index == 3) {
              crr.push(item);
            }
          });
          var arr = [...fromLonLat(brr), ...crr];
          this.localList = arr;
          this.map.addLayer(layer);
        },
        function(error) {
          alert(`ERROR: ${error.message}`);
        },
        {
          enableHighAccuracy: true
        }
      );
    },
    locate(source) {
      if (!source.isEmpty()) {
        this.map.getView().fit(this.localList, {
          maxZoom: 19,
          duration: 500,
          padding: [300, 300, 0, 0]
        });
      }
    },
    onFeatureSelect(feature) {
      console.log(feature);
    },
    manyLocal() {
      var image = new CircleStyle({
        radius: 5,
        fill: new Fill({
          color: "red"
        }),
        stroke: new Stroke({ color: "red", width: 1 })
      });
      var styles = {
        Point: new Style({
          image: image
        }),
        MultiPoint: new Style({
          image: image
        }),
        Circle: new Style({
          stroke: new Stroke({
            color: "red",
            width: 5
          }),
          fill: new Fill({
            color: "rgba(255,0,0,0.2)"
          })
        })
      };
      console.log(styles);
      localInfo.getManyLocal().then(res => {
        var vectorSource = new VectorSource({
          features: new GeoJSON().readFeatures(res.data)
        });
        vectorSource.addFeature(new Feature(new Circle([5e6, 7e6], 1e6)));
        var vectorLayer = new VectorLayer({
          source: vectorSource,
          style: new Style({
            image: new Icon({
              // opacity: 0,
              src:
                "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1594359193211&di=1d6bb819a5daa724ff65cc4d011d4d42&imgtype=0&src=http%3A%2F%2Fku.90sjimg.com%2Felement_pic%2F17%2F10%2F27%2F05dc60e54e3aa5d093cdc32611303643.jpg",
              scale: 0.05
            })
          })
        });
        this.map.addLayer(vectorLayer);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.locate {
  top: 6em;
  left: 0.5em;
}
#map {
  height: 100%;
}
/*隐藏ol的一些自带元素*/
.ol-attribution,
.ol-zoom {
  display: none;
}
/* 弹窗样式 */
.popup {
  min-width: 280px;
  margin-bottom: 1rem;
  position: relative;
  background: #fff;
  padding: 8px 16px;
  display: flex;
  flex-direction: column;

  /* 弹窗下方的小三角形 */
  &::after {
    display: block;
    content: "";
    width: 0;
    height: 0;
    position: absolute;
    border: 12px solid transparent;
    border-top-color: #fff;
    bottom: -23px;
    left: 50%;
    transform: translateX(-50%);
  }
}
/* 关闭弹窗按钮 */
.icon-close {
  cursor: pointer;
  align-self: flex-end;
  margin-bottom: 10px;
}
</style>
